#include <string>
#include <vector>
using namespace std;
/*
 * @lc app=leetcode.cn id=93 lang=cpp
 *
 * [93] 复原 IP 地址
 */

// @lc code=start
class Solution {
public:
    vector<string> res;
    vector<string> restoreIpAddresses(string s) {
        string temp;
        dfs(temp, 0, s, 0);
        return res;
    }

    void dfs(string & now, int index, const string & s, int dot) {
        int num = 0, i = 0;
        if (index >= s.size()) return;
        if (dot == 3) {
            if (s[index] == '0' && index < s.size() - 1) return;
            if (s.size() - index > 3) return;
            for (int i = index; i < s.size(); i++)
                num = num * 10 + s[i] - '0';
            string x = now;
            x.append(s.substr(index));
            if (num <= 255) res.push_back(x);

            return;
        }
        if (s[index] == '0') {
            now.append("0.");
            dfs(now, index + 1, s, dot + 1);
            now.pop_back(); now.pop_back();
            return;
        }
        
        for (i = 0; i < 3; i++) {
            num = num * 10 + s[index + i] - '0';
            if (num > 255) break;
            now.push_back(s[index + i]);
            now.push_back('.');
            dfs(now, index + i + 1, s, dot + 1);
            now.pop_back(); // 没有完全回溯
        }
        while (i--) now.pop_back();
    }
};
// @lc code=end

